<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item>信息流管理</el-breadcrumb-item>
      <el-breadcrumb-item>产品管理</el-breadcrumb-item>
    </el-breadcrumb>

    <Container class="u-mb15">
      <!-- 筛选 -->
      <el-form
        inline
        class="m-form--filter"
      >
        <el-form-item>
          <el-select
            class="u-w160"
            size="mini"
            filterable
            placeholder="请选择客户名称"
            v-model="filter.customerId"
            @change="handleChangeCustomerOptions"
          >
            <el-option
              v-for="item in customerOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            class="u-w160"
            size="mini"
            filterable
            placeholder="请选择产品"
            v-model="filter.productId"
            @change="handleChangeProductOptions"
          >
            <el-option
              v-for="item in productOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            class="u-w160"
            size="mini"
            filterable
            placeholder="请选择平台"
            v-model="filter.platformId"
          >
            <el-option
              v-for="item in platformOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            class="u-w160"
            size="mini"
            filterable
            placeholder="请选择产品状态"
            v-model="filter.status"
          >
            <el-option
              v-for="(item, index) in [{label: '全部产品状态', value: null}].concat(PRODUCE_STATUS_OPTION)"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            class="u-w160"
            size="mini"
            filterable
            placeholder="请选择AE负责人"
            v-model="filter.aeId"
          >
            <el-option
              v-for="item in [{name: '全部AE', id: null}].concat(aeOptions)"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-select
            class="u-w160"
            size="mini"
            filterable
            placeholder="请选择商务负责人"
            v-model="filter.businessId"
          >
            <el-option
              v-for="item in [{name: '全部商务', id: null}].concat(businessOptions)"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            size="mini"
            @click="search"
          >查询</el-button>
        </el-form-item>
      </el-form>
    </Container>

    <Container>
      <!-- 表格操作 -->
      <el-form
        inline
        class="m-table--handle"
      >
        <el-form-item>
          <el-button
            size="mini"
            type="primary"
            @click="$router.push({
              name: 'flow-product-detail',
              query: {
                action: 'create'
              }
            })"
          >新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            size="mini"
            type="primary"
            @click="multiChangeState"
          >设置产品状态</el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            size="mini"
            type="primary"
            @click="multiChangeAe"
          >设置AE</el-button>
        </el-form-item>
        <el-form-item>
          <el-button
            size="mini"
            type="primary"
            @click="multiChangeBusiness"
          >设置商务</el-button>
        </el-form-item>
        <br>
        <el-form-item>
            <ImportTable :importName="importProductName" :importUrl="importProductUrl"></ImportTable>
        </el-form-item>
        <el-form-item>
            <ImportTable :importName="importMineName" :importUrl="importMineUrl"></ImportTable>
        </el-form-item>
        <el-form-item>
            <ImportTable :importName="importCustomerName" :importUrl="importCustomerUrl"></ImportTable>
        </el-form-item>
        <el-form-item>
            <ImportTable :importName="importServeName" :importUrl="importServeUrl"></ImportTable>
        </el-form-item>
        <el-form-item>
          <el-button
              @click="exportExcel('/manage/api/bus/product/export',requestSearch)"
              size="mini"
            >导出</el-button>
        </el-form-item>
        <el-form-item>
          <el-link type="primary" :underline="false" @click="importVisible = true">下载导入模版</el-link> 
        </el-form-item>





   <CustomTableColumn :columns.sync="tableColumn" />
      </el-form>
      <!-- 表格 -->
      <el-table
        border
        stripe
        :data="tableData"
        @selection-change="changeTableSelection"
      >
        <el-table-column
          type="selection"
          width="35"
          fixed
        >
        </el-table-column>
        <el-table-column
          align="center"
          v-for="(item, index) in filterTableColumn"
          :label="item.label"
          :key="index"
          :prop="item.prop"
          :sortable="item.sortable"
        >
          <template slot-scope="scope">
            <!-- 我方运营返点 -->
            <template v-if="item.prop === '__ourRetabes'">
              <div>{{scope.row.__ourRetabes}}</div>
              <el-button
                type="text"
                @click="openDialogRebate({ operator: 1, productId: scope.row.id, rebates: scope.row.ourRetabes })"
              >修改 <i class="el-icon-edit"></i></el-button>
            </template>
            
            <!-- 客户运营返点 -->
            <template v-else-if="item.prop === '__customerRetabes'">
              <div>{{scope.row.__customerRetabes}}</div>
              <el-button
                type="text"
                @click="openDialogRebate({ operator: 2, productId: scope.row.id, rebates: scope.row.customerRetabes })"
              >修改 <i class="el-icon-edit"></i></el-button>
            </template>
              <!-- 服务费率 -->
            <template v-else-if="item.prop === '__serviceRate'">
              <div>{{scope.row.__serviceRate}}</div>
              <el-button
                type="text"
                @click="openDialogServe({productId: scope.row.id, serviceRate: scope.row.serviceRate })"
              >修改 <i class="el-icon-edit"></i></el-button>
            </template>
            <!-- AE -->
            <template v-else-if="item.prop === 'aePrincipal'">
              <div>{{scope.row.aePrincipal ? scope.row.aePrincipal : '-'}}</div>
              <el-button
                type="text"
                @click="openDialogAe({id: scope.row.id, principal: scope.row.aeId, startDate: scope.row.aeDate})"
              >修改 <i class="el-icon-edit"></i></el-button>
            </template>
            <!-- 商务 -->
            <template v-else-if="item.prop === 'businessPrincipal'">
              <div>{{scope.row.businessPrincipal ? scope.row.businessPrincipal : '-'}}</div>
              <el-button
                type="text"
                @click="openDialogBusiness({id: scope.row.id, principal: scope.row.businessId, startDate: scope.row.businessDate})"
              >修改 <i class="el-icon-edit"></i></el-button>
            </template>
            <!-- 产品状态 -->
            <template v-else-if="item.prop === 'status'">
              <div>{{mapOptionLabel(PRODUCE_STATUS_OPTION, scope.row.status)}}</div>
              <el-button
                type="text"
                @click="openDialogState(scope.row)"
              >修改 <i class="el-icon-edit"></i></el-button>
            </template>
            <!-- 关联账号 -->
            <template v-else-if="item.prop === 'accountCount'">
              <el-button
                v-if="scope.row.accountCount > 0"
                type="text"
                @click="$router.push({
                  name: 'flow-account',
                  query: {
                    productId: scope.row.productNameId,
                    platformId: scope.row.platformId,
                    customerId: scope.row.customerId
                  }
                })"
              >{{scope.row.accountCount}}</el-button>
              <template v-else>{{scope.row.accountCount}}</template>
            </template>
            <!-- 其他 -->
            <template v-else>{{scope.row[item.prop]}}</template>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          align="center"
          width="180"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              @click="$router.push({
                name: 'flow-product-detail',
                query: {
                  action: 'edit',
                  id: scope.row.id
                }
              })"
            >编辑</el-button>
            <el-button
              type="text"
              @click="$router.push({
                name: 'flow-product-detail',
                query: {
                  action: 'detail',
                  id: scope.row.id
                }
              })"
            >查看</el-button>
            <!-- <el-button
              type="text"
              @click="removeProduct(scope.row.id)"
              v-if="scope.row.accountCount === 0"
            >删除</el-button> -->
            <el-button
              type="text"
              @click="$router.push({
                name: 'flow-product-status-detail',
                query: {
                  id: scope.row.id,
                  title: `${scope.row.platformName}-${scope.row.productName}-${scope.row.customerName}`
                }
              })"
            >状态详情</el-button>
            <el-button
              type="text"
              @click="$router.push({
                name: 'flow-product-rebate-detail',
                query: {
                  id: scope.row.id,
                  title: `${scope.row.platformName}-${scope.row.productName}-${scope.row.customerName}`
                }
              })"
            >返点详情</el-button>
            <el-button
              type="text"
              @click="$router.push({
                name: 'flow-product-principal-detail',
                query: {
                  id: scope.row.id,
                  title: `${scope.row.platformName}-${scope.row.productName}-${scope.row.customerName}`
                }
              })"
            >AE/商务详情</el-button>
            <el-button
              type="text"
              @click="$router.push({
                name: 'flow-product-serve-detail',
                query: {
                  id: scope.row.id,
                  title: `${scope.row.platformName}-${scope.row.productName}-${scope.row.customerName}`
                }
              })"
            >服务费率详情</el-button>
              <el-button
               type="text"
                size="mini"
                v-if="scope.row.accountCount == 0"
                @click="handleDelete(scope.row.id)"
              >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        background
        :page-sizes="[50, 100, 500, 1000]"
        :page-size="page.pageSize"
        layout="total, prev, pager, next, sizes"
        :total="pageTotal"
        @size-change="handlePagerSizeChange"
        @current-change="handlePagerCurrentChange"
      />
    </Container>

    <!-- AE -->
    <el-dialog
      title="对接AE"
      :visible.sync="dialogAeVisible"
      width="350px"
    >
      <el-form
        label-width="110px"
        :model="dialogAeData"
        :rules="dialogAeRules"
        ref="dialogAeForm"
      >
        <el-form-item
          label="AE负责人"
          required
          prop="principal"
        >
          <el-select
            class="u-w200"
            size="mini"
            filterable
            placeholder="请选择AE负责人"
            v-model="dialogAeData.principal"
          >
            <el-option
              v-for="item in aeOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="开始日期"
          required
          prop="startDate"
        >
          <el-date-picker
            class="u-w200"
            type="date"
            placeholder="选择日期"
            size="small"
            value-format="yyyy-MM-dd"
            :clearable="false"
            v-model="dialogAeData.startDate"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>

      <el-row
        type="flex"
        justify="end"
      >
        <el-button
          size="small"
          @click="dialogAeVisible = false"
        >取消</el-button>
        <el-button
          type="primary"
          size="small"
          @click="handleDialogAeSure"
        >确定</el-button>
      </el-row>
    </el-dialog>

    <!-- 商务 -->
    <el-dialog
      title="对接商务"
      :visible.sync="dialogBusinessVisible"
      width="350px"
    >
      <el-form
        label-width="110px"
        :model="dialogBusinessData"
        :rules="dialogBusinessRules"
        ref="dialogBusinessForm"
      >
        <el-form-item
          label="商务负责人"
          required
          prop="principal"
        >
          <el-select
            class="u-w200"
            size="mini"
            filterable
            placeholder="请选择商务负责人"
            v-model="dialogBusinessData.principal"
          >
            <el-option
              v-for="item in businessOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="开始日期"
          required
          prop="startDate"
        >
          <el-date-picker
            class="u-w200"
            type="date"
            placeholder="选择日期"
            size="small"
            value-format="yyyy-MM-dd"
            :clearable="false"
            v-model="dialogBusinessData.startDate"
          >
          </el-date-picker>
        </el-form-item>
      </el-form>

      <el-row
        type="flex"
        justify="end"
      >
        <el-button
          size="small"
          @click="dialogBusinessVisible = false"
        >取消</el-button>
        <el-button
          type="primary"
          size="small"
          @click="handleDialogBusinessSure"
        >确定</el-button>
      </el-row>
    </el-dialog>

    <!-- 产品状态 -->
    <el-dialog
      title="设置产品状态"
      :visible.sync="dialogStateVisible"
      width="460px"
    >
      <el-form
        label-width="120px"
        :model="dialogStateData"
        :rules="dialogStateRules"
        ref="dialogStateForm"
      >
        <el-form-item label="产品当前状态">
          <el-select
            class="u-w300"
            size="small"
            filterable
            v-model="dialogStateData.status"
          >
            <el-option
              v-for="(item, index) in PRODUCE_STATUS_OPTION"
              :key="index"
              :label="item.label"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="产品投放日期"
          v-if="dialogStateData.status === 4"
        >
          <el-date-picker
            class="u-w300"
            type="date"
            placeholder="选择日期"
            size="small"
            value-format="yyyy-MM-dd"
            :clearable="false"
            v-model="dialogStateData.startDate"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label="产品停投日期"
          v-if="dialogStateData.status === 5"
        >
          <el-date-picker
            class="u-w300"
            type="date"
            placeholder="选择日期"
            size="small"
            value-format="yyyy-MM-dd"
            :clearable="false"
            v-model="dialogStateData.stopDate"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item
          label="产品停投原因"
          v-if="dialogStateData.status === 5"
        >
          <el-input
            type="textarea"
            class="u-w300"
            size="small"
            rows="5"
            maxlength="200"
            v-model.trim="dialogStateData.stopReason"
          ></el-input>
        </el-form-item>
      </el-form>

      <el-alert
        class="u-mb20"
        type="warning"
        :closable="false"
        v-if="dialogStateData.status === 5"
      >
        注：确定产品停投,系统将自动停用此产品关联的全部账号！
      </el-alert>

      <el-row
        type="flex"
        justify="end"
      >
        <el-button
          size="small"
          @click="dialogStateVisible = false"
        >取消</el-button>
        <el-button
          type="primary"
          size="small"
          @click="handleDialogStateSure"
        >确定</el-button>
      </el-row>
    </el-dialog>

    <!-- 运营返点 -->
   <el-dialog
      :title="dialogRebateTitle"
      :visible.sync="dialogRebateVisible"
      width="442px"
    >
      <el-form
        :model="dialogRebateData"
        ref="dialogRebateForm"
      >
        <el-row v-if="!dialogRebateData.rebates.length">
          <el-button
            size="small"
            type="primary"
            @click="addRebates"
          >添加</el-button>
        </el-row>
        <el-row
          v-for="(item, index) in dialogRebateData.rebates"
          :key="index"
        >
          <el-form-item
            class="u-dib"
            :prop="'rebates.' + index + '.startDate'"
            :rules="dialogRebateRules.startDate"
          >

            <el-date-picker
              class="u-w160"
              type="date"
              placeholder="选择日期"
              size="small"
              v-model="item.startDate"
              value-format="yyyy-MM-dd"
              :clearable="false"
              :picker-options="dialogRebatePickerOptions"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item
            class="u-dib u-ml10"
            :prop="'rebates.' + index + '.rebates'"
            :rules="dialogRebateRules.rebates"
          >
            <el-input
              class="u-w75"
              size="small"
              placeholder="请输入返点"
              v-model.trim="item.rebates"
            ></el-input>
            %
            <el-button
              size="small"
              type="primary"
              class="u-ml10"
              @click="addRebates"
            >添加</el-button>
            <el-button
              size="small"
              class="u-ml10"
              @click="removeRebates(index)"
            >删除</el-button>
          </el-form-item>
        </el-row>
      </el-form>

      <el-row
        type="flex"
        justify="end"
      >
        <el-button
          size="small"
          @click="dialogRebateVisible = false"
        >取消</el-button>
        <el-button
          type="primary"
          size="small"
          @click="handleDialogRebateSure"
        >确定</el-button>
      </el-row>
    </el-dialog>
    
    <el-dialog
      title="服务费率"
      :visible.sync="dialogServeVisible"
      width="442px"
    >
       <el-form
        :model="dialogServeData"
        ref="dialogServeForm"
      >
        <el-row v-if="!dialogServeData.serviceRate.length">
          <el-button
            size="small"
            type="primary"
            @click="addServiceRates"
          >添加</el-button>
        </el-row>
        <el-row
          v-for="(item, index) in dialogServeData.serviceRate"
          :key="index"
        >
          <el-form-item
            class="u-dib"
            :prop="'serviceRate.' + index + '.startDate'"
            :rules="dialogServeRules.startDate"
          >

            <el-date-picker
              class="u-w160"
              type="date"
              placeholder="选择日期"
              size="small"
              v-model="item.startDate"
              value-format="yyyy-MM-dd"
              :clearable="false"
              :picker-options="dialogServePickerOptions"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item
            class="u-dib u-ml10"
            :prop="'serviceRate.' + index + '.serviceRate'"
            :rules="dialogServeRules.serviceRate"
          >
            <el-input
              class="u-w75"
              size="small"
              placeholder="请输入返点"
              v-model.trim="item.serviceRate"
            ></el-input>
            %
            
             <el-button
              size="small"
              type="primary"
              class="u-ml10"
              @click="addServiceRates"
            >添加</el-button>
            <el-button
              size="small"
              class="u-ml10"
              @click="removeserviceRate(index)"
            >删除</el-button>
          </el-form-item>
        </el-row>
      </el-form>
      <el-row
        type="flex"
        justify="end"
      >
        <el-button
          size="small"
          @click="dialogServeVisible = false"
        >取消</el-button>
        <el-button
          type="primary"
          size="small"
          @click="handleDialogServeSure"
        >确定</el-button>
      </el-row>
    </el-dialog>

    <el-dialog
      class="dialog"
      title="导入模版下载"
      :visible.sync="importVisible"
      width="300"
      >
      <el-form >
        <el-form-item >
         <el-link type="primary" :underline="false" @click="downloadProductTemplate">产品导入模版 下载</el-link> 
        </el-form-item>
        <el-form-item >
         <el-link type="primary" :underline="false" @click="downloadMineTemplate">我方运营返点导入模板 下载</el-link>
        </el-form-item>
        <el-form-item >
         <el-link type="primary" :underline="false" @click="downloadCustomerTemplate">客户运营返点导入模板 下载</el-link>
        </el-form-item>
        <el-form-item >
         <el-link type="primary" :underline="false" @click="downloadServeTemplate">服务费率导入模版 下载</el-link>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="importVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { cloneDeep } from "lodash";
import moment from "moment";
import Container from "@/components/container";
import CustomTableColumn from "@/components/custom-table-column";
import ImportTable from "@/components/import-table.vue";


import { PRODUCE_STATUS_OPTION } from "@/assets/js/flow-option";
import { mapOptionLabel, getStrLen } from "@/util";
import { exportExcel } from '@/utils/fileDown.js';

export default {
  name: "flow-product",
  components: {
    Container,
    CustomTableColumn,
    ImportTable
  },
  data() {
    return {
      PRODUCE_STATUS_OPTION,
      importProductName:'产品导入',
      importMineName:'我方运营返点导入',
      importCustomerName:'客户运营返点导入',
      importServeName:'服务费率导入',
      importProductUrl:'/manage/api/bus/product/import_product',
      importMineUrl:'/manage/api/bus/product/import_our_rebates',
      importCustomerUrl:'/manage/api/bus/product/import_customer_rebates',
      importServeUrl:'/manage/api/bus/product/import_service_rates',
      importVisible:false,
      // 下拉
      customerOptions: [],
      productOptions: [],
      platformOptions: [],
      aeOptions: [],
      businessOptions: [],

      // 筛选
      filter: {
        customerId: null,
        productId: null,
        platformId: null,
        status: null,
        aeId: null,
        businessId: null
      },

      // 产品状态
      dialogStateVisible: false,
      dialogStateData: {},
      dialogStateRules: {
        stopReason: {
          validator: (rule, value, callback) => {
            if (getStrLen(value) > 200) {
              callback(new Error("产品停投原因最多200个字符"));
            } else {
              callback();
            }
          },
          trigger: ["change", "blur"]
        }
      },
      // 服务
      dialogServeVisible:false,
      dialogServeData: {
        serviceRate:[{ serviceRate: 0, startDate: "" }],
      },
      dialogServeRules: {
        startDate: {
          required: true,
          message: "请选择日期",
          trigger: ["blur", "change"]
        },
        serviceRate: {
          required: true,
          validator: (rule, value, callback) => {
            if (value === "") {
              callback(new Error("请输入返点"));
            } else if (isNaN(value) || value < 0 || value > 100) {
              callback(new Error("请输入0~100"));
            } else if (
              String(value).length > String(Number(value).toFixed(2)).length
            ) {
              callback(new Error("最多保留2位小数"));
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        }
      },
      // AE
      dialogAeVisible: false,
      dialogAeData: {},
      dialogAeRules: {
        principal: {
          required: true,
          message: "请输入AE负责人",
          trigger: ["blur", "change"]
        },
        startDate: {
          required: true,
          message: "请选择日期",
          trigger: ["blur", "change"]
        }
      },

      // 商务
      dialogBusinessVisible: false,
      dialogBusinessData: {},
      dialogBusinessRules: {
        principal: {
          required: true,
          message: "请输入商务负责人",
          trigger: ["blur", "change"]
        },
        startDate: {
          required: true,
          message: "请选择日期",
          trigger: ["blur", "change"]
        }
      },

      // 运营返点
      dialogRebateTitle: "",
      dialogRebateVisible: false,
      dialogRebateData: {
        rebates: []
      },
      dialogRebateRules: {
        startDate: {
          required: true,
          message: "请选择日期",
          trigger: ["blur", "change"]
        },
        rebates: {
          required: true,
          validator: (rule, value, callback) => {
            if (value === "") {
              callback(new Error("请输入返点"));
            } else if (isNaN(value) || value < 0 || value > 100) {
              callback(new Error("请输入0~100"));
            } else if (
              String(value).length > String(Number(value).toFixed(2)).length
            ) {
              callback(new Error("最多保留2位小数"));
            } else {
              callback();
            }
          },
          trigger: ["blur", "change"]
        }
      },

      // 表格
      tableData: [],
      tableSelectionData: [],
      tableColumn: [
        {
          label: "平台名称",
          prop: "platformName",
          visible: true
        },
        {
          label: "客户名称",
          prop: "customerName",
          visible: true
        },
        {
          label: "客户角色",
          prop: "customerRole",
          visible: true
        },
        {
          label: "产品名称",
          prop: "productName",
          visible: true
        },
        {
          label: "我方运营最新返点",
          prop: "__ourRetabes",
          visible: true,
          sortable: true
        },
        {
          label: "客户运营最新返点",
          prop: "__customerRetabes",
          visible: true,
          sortable: true
        },
        {
          label: "服务费率",
          prop: "__serviceRate",
          visible: true,
          sortable: true
        },
        {
          label: "AE负责人",
          prop: "aePrincipal",
          visible: true
        },
        {
          label: "商务负责人",
          prop: "businessPrincipal",
          visible: true
        },
        {
          label: "产品状态",
          prop: "status",
          visible: true
        },
        {
          label: "关联账号",
          prop: "accountCount",
          visible: true
        }
      ],
      page: {
        pageNo: 1,
        pageSize: 50
      },
      pageTotal: 0
    };
  },
  computed: {
    requestSearch() {
      return {
        ...this.filter,
        ...this.page
      }
    },
    filterTableColumn() {
      return this.tableColumn.filter(item => item.visible);
    },
    // 返点日期不可重复
    dialogRebatePickerOptions() {
      let vm = this;
      return {
        disabledDate(date) {
          return vm.dialogRebateData.rebates.some(item => {
            return item.startDate === moment(date).format("YYYY-MM-DD");
          });
        }
      };
    },
     // 返点日期不可重复
    dialogServePickerOptions() {
      let vm = this;
      return {
        disabledDate(date) {
          return vm.dialogServeData.serviceRate.some(item => {
            return item.startDate === moment(date).format("YYYY-MM-DD");
          });
        }
      };
    }
  },
  methods: {
    mapOptionLabel,
    exportExcel,
    handleDelete(id) {
      this.$confirm("是否删除此账号？删除后不可恢复！", "删除", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
           this.$http({
            method: "post",
            url: "/manage/api/bus/product/del",
            params: {
              productId: id
            }
          }).then(res => {
            if (res.data.code === 0) {
              this.$message.success("删除成功!");
              this.getTable();
            } else {
              this.$message.error(res.data.msg);
            }
          });
        })
        .catch(() => {});
    },
     // 下载模板
    downloadProductTemplate() {
      location.href = "https://s.55duanzi.com/CMS/产品导入表格.xls";
    },
    downloadMineTemplate() {
      location.href = "https://s.55duanzi.com/CMS/我方运营返点导入表格.xls";
    },
    downloadCustomerTemplate() {
      location.href = "https://s.55duanzi.com/CMS/客户运营返点导入表格.xls";
    },
    downloadServeTemplate() {
      location.href = "https://s.55duanzi.com/CMS/服务费率导入表格.xls";
    },
    // 下拉
    fetchCustomerOptions() {
      this.$http({
        method: "get",
        url: "/manage/api/bus/customer/get_customer_name",
        params: {
          status: 0
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.customerOptions = [
            {
              id: null,
              name: "全部客户"
            }
          ].concat(res.data.data);
        }
      });
    },
    fetchProductOptions(customerId = 0) {
      this.$http({
        method: "get",
        url: "/manage/api/bus/product/get_all_product",
        params: { customerId: Number(customerId) }
      }).then(res => {
        if (res.data.code === 0) {
          this.productOptions = [
            {
              id: null,
              name: "全部产品"
            }
          ].concat(res.data.data);
        }
      });
    },
    fetchPlatformOptions(customerId = 0, productId = 0) {
      this.$http({
        method: "get",
        url: "/manage/api/bus/platform/get_platform",
        params: {
          status: 0,
          customerId: Number(customerId),
          productId: Number(productId)
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.platformOptions = [
            {
              id: null,
              name: "全部平台"
            }
          ].concat(res.data.data);
        }
      });
    },
    fetchAeOptions() {
      this.$http({
        method: "get",
        url: "/manage/api/bus/product/get_position",
        params: {
          position: 2
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.aeOptions = res.data.data;
        }
      });
    },
    fetchBusinessOptions() {
      this.$http({
        method: "get",
        url: "/manage/api/bus/product/get_position",
        params: {
          position: 1
        }
      }).then(res => {
        if (res.data.code === 0) {
          this.businessOptions = res.data.data;
        }
      });
    },
    handleChangeCustomerOptions() {
      this.filter.productId = null;
      this.filter.platformId = null;
      this.fetchProductOptions(this.filter.customerId);
    },
    handleChangeProductOptions() {
      this.filter.platformId = null;
      this.fetchPlatformOptions(this.filter.customerId, this.filter.productId);
    },

    // AE
    multiChangeAe() {
      if (!this.tableSelectionData.length) {
        return this.$message.warning("请选择需要操作的选项！");
      }
      this.openDialogAe({
        id: this.tableSelectionData.map(item => item.id).join()
      });
    },
    handleDialogAeSure() {
      this.$refs.dialogAeForm.validate(valid => {
        if (valid) {
          this.$http({
            method: "post",
            url: "/manage/api/bus/product/principal",
            data: this.dialogAeData
          }).then(res => {
            if (res.data.code === 0) {
              this.$message.success("操作成功！");
              this.dialogAeVisible = false;
              this.getTable();
            }
          });
        }
      });
    },
    openDialogAe({ id, principal = "", startDate = "" }) {
      this.dialogAeData = {
        ids: String(id),
        position: 2,
        principal,
        startDate
      };
      this.$refs.dialogAeForm && this.$refs.dialogAeForm.resetFields();
      this.dialogAeVisible = true;
    },
    // 商务
    multiChangeBusiness() {
      if (!this.tableSelectionData.length) {
        return this.$message.warning("请选择需要操作的选项！");
      }
      this.openDialogBusiness({
        id: this.tableSelectionData.map(item => item.id).join()
      });
    },
    handleDialogBusinessSure() {
      this.$refs.dialogBusinessForm.validate(valid => {
        if (valid) {
          this.$http({
            method: "post",
            url: "/manage/api/bus/product/principal",
            data: this.dialogBusinessData
          }).then(res => {
            if (res.data.code === 0) {
              this.$message.success("操作成功！");
              this.dialogBusinessVisible = false;
              this.getTable();
            }
          });
        }
      });
    },
    openDialogBusiness({ id, principal = "", startDate = "" }) {
      this.dialogBusinessData = {
        ids: String(id),
        position: 1,
        principal,
        startDate
      };
      this.$refs.dialogBusinessForm &&
        this.$refs.dialogBusinessForm.resetFields();
      this.dialogBusinessVisible = true;
    },

    // 状态
    multiChangeState() {
      if (!this.tableSelectionData.length) {
        return this.$message.warning("请选择需要操作的选项！");
      }
      this.openDialogState({
        id: this.tableSelectionData.map(item => item.id).join()
      });
    },
    handleDialogStateSure() {
      this.$refs.dialogStateForm.validate(valid => {
        if (valid) {
          this.$http({
            method: "post",
            url: "/manage/api/bus/product/status",
            data: this.dialogStateData
          }).then(res => {
            if (res.data.code === 0) {
              this.$message.success("操作成功！");
              this.dialogStateVisible = false;
              this.getTable();
            }
          });
        }
      });
    },
    openDialogState({
      id,
      status = 1,
      startDate = "",
      stopDate = "",
      stopReason = ""
    }) {
      this.dialogStateData = {
        ids: String(id),
        status,
        startDate,
        stopDate,
        stopReason
      };
      this.$refs.dialogStateForm && this.$refs.dialogStateForm.resetFields();
      this.dialogStateVisible = true;
    },

    // 返点
    handleDialogRebateSure() {
      this.$refs.dialogRebateForm.validate(valid => {
        if (valid) {
          this.$http({
            method: "post",
            url: "/manage/api/bus/product/rebates",
            data:{
              ... this.dialogRebateData,
              // rebates: this.dialogRebateData.rebates[0]
            }
          }).then(res => {
            if (res.data.code === 0) {
              this.$message.success("操作成功！");
              this.dialogRebateVisible = false;
              this.getTable();
            }else{
              this.$message.error(res.data.msg);
              this.dialogRebateVisible = false;
              this.getTable();
            }
          });
        }
      });
    },
    // 服务费率
    openDialogServe({productId,serviceRate}){
      this.dialogServeData = {
        productId: productId,
        serviceRate:serviceRate
        // serviceRate:serviceRate.length > 0 ? serviceRate :[{ serviceRate: 0, startDate: "" }]
      };
      // console.log(this.dialogServeData)
        this.$refs.dialogServeForm && this.$refs.dialogServeForm.resetFields();
        this.dialogServeVisible = true;
    },
    handleDialogServeSure() {
      this.$refs.dialogServeForm.validate(valid => {
        if (valid) {
          this.$http({
            method: "post",
            url: "/manage/api/bus/product/service_rate",
            data: {
              ...this.dialogServeData,
              // serviceRate:this.dialogServeData.serviceRate[0]
            },
          }).then(res => {
            if (res.data.code === 0) {
              this.$message.success("操作成功！");
              this.dialogServeVisible = false;
              this.getTable();
            }else{
              this.$message.error(res.data.msg);
              this.dialogServeVisible = false;
               this.getTable();
              
            }
            
          });
        }
      });
    },
    addRebates() {
      this.dialogRebateData.rebates.push({ rebates: 0, startDate: "" });
    },
    removeRebates(index) {
      this.dialogRebateData.rebates.splice(index, 1);
    },
    addServiceRates() {
      this.dialogServeData.serviceRate.push({ serviceRate: 0, startDate: "" });
    },
    removeserviceRate(index) {
      this.dialogServeData.serviceRate.splice(index, 1);
    },
    setCurrentRetabes(data = []) {
      let len = data.length;
      if (len) {
        return data[len - 1].rebates+'%';
      }
      return '-';
    },
    setCurrentserviceRate(data = []) {
      let len = data.length;
      if (len) {
        return data[len - 1].serviceRate+'%';
      }
      return '-';
    },
    appendCurrentRetabes(data = []) {
      return data.map(item => {
        return {
          ...item,
          __customerRetabes: this.setCurrentRetabes(item.customerRetabes),
          __ourRetabes: this.setCurrentRetabes(item.ourRetabes),
          __serviceRate: this.setCurrentserviceRate(item.serviceRate)
        };
      });
    },
    openDialogRebate(data) {
      this.dialogRebateTitle =
        data.operator === 1 ? "我方运营返点" : "客户运营返点";
      this.dialogRebateData = cloneDeep(data);
      this.$refs.dialogRebateForm && this.$refs.dialogRebateForm.resetFields();
      this.dialogRebateVisible = true;
    },

    // 列表
    search() {
      this.page.pageNo = 1;
      this.getTable();
    },
    getTable() {
      this.$http({
        method: "post",
        url: "/manage/api/bus/product/get_list",
        data: {
          ...this.filter,
          ...this.page
        }
      }).then(res => {
        if (res.data.code === 0) {
          let data = res.data.data;
          this.tableData = this.appendCurrentRetabes(data.list);
          this.pageTotal = data.listCount;
        } else {
          this.$message.error(res.data.msg);
        }
      });
    },
    removeProduct() {
      this.$confirm("删除后不可恢复！", "是否删除此条数据？", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {})
        .catch(() => {});
    },
    changeTableSelection(data) {
      this.tableSelectionData = data;
    },
    handlePagerSizeChange(v) {
      this.page.pageSize = v;
      this.getTable();
    },
    handlePagerCurrentChange(v) {
      this.page.pageNo = v;
      this.getTable();
    }
  },
  activated(){
    this.getTable();
  },
  created() {
    this.fetchCustomerOptions();
    this.fetchProductOptions();
    this.fetchPlatformOptions();
    this.fetchAeOptions();
    this.fetchBusinessOptions();
  }
};
</script>